package com.yupi.project.service.impl;

import com.yupi.project.common.ErrorCode;
import com.yupi.project.common.ResultUtils;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.mapper.UserInterfaceInfoMapper;
import com.yupi.project.service.UserInterfaceInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yuapicommon.model.entity.UserInterfaceInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户调用接口关系 服务实现类
 * </p>
 *
 * @author 毛哥
 * @since 2025-05-23
 */
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo> implements UserInterfaceInfoService {
    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建时，所有参数必须非空
        if (add) {
            if (userInterfaceInfo.getInterfaceInfoId() <= 0 || userInterfaceInfo.getUserId() <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口或用户不存在");
            }
        }
        if (userInterfaceInfo.getLeftNum() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余次数不能小于 0");
        }
    }

    /**
     * 修改调用记录
     * @param userId
     * @param InterfaceId
     */
    @Override
    public boolean updateNum(int userId, int InterfaceId) {
        if (userId <= 0 || InterfaceId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        boolean update = lambdaUpdate().eq(UserInterfaceInfo::getUserId, userId)
                .eq(UserInterfaceInfo::getInterfaceInfoId, InterfaceId)
                .gt(UserInterfaceInfo::getLeftNum, 0)
                .setSql("leftNum=leftNum -1,totalNum=totalNum +1")
                .update();
        return update;
    }
}
